<template>
<el-container>
  <el-main class="leftMain">
    <system-tree
      :show-tabs="true"
      show-min-type="2"
      :show-device-index="true"
      :second-action="false"
    ></system-tree>
  </el-main>
  <el-main class="rightMain">
    <bs-main class="bsMain">
      <sys-manage-condition
        slot="header"
        ref="condition"
        :allSize="allSize" 
        :pageData="pageData"
        :requestParam="requestParam"
        @do-refresh="doRefresh"
        @load-userlist="loadUserList"
      ></sys-manage-condition>
      <list
        ref="userList"
        class="right"
        :table-tag="tableName"
        :list-data="userList"
        :has-select="true"
        :list-cols="columns"
        :action-opts="actionOpts"
        :init-cols-props.sync="initColsProps"
        height="calc(100vh - 230px)"
        :init-headmune-flag="initHeadmuneFlag"
        @init-table="initTable"
        @sort="handleSort"
        @filter="handleFilter"
        @selection-change="handleSelectionChange"
      ></list>
      <pagination
        slot="footer"
        :total="pageData.total"
        :page="pageData.page"
        :limit="pageData.limit"
        :showAllChecked="true" 
        :allChecked="allSize"
        @all="handleChangeAllSize"
        @pagination="loadUserList"
      ></pagination>
    </bs-main>
    <user-edit-dialog @do-refresh="loadUserList"></user-edit-dialog>
  </el-main>
</el-container>
</template>

<script>
import List from '@/components/List'
import Pagination from '@/components/Pagination'
import SysManageCondition from './components/SysManageCondition'
// import SystemTree from '../components/SystemTree'
import SystemTree from '../SystemTree'
import UserEditDialog from './components/UserEditDialog'
export default {
  components: {
    List,
    SysManageCondition,
    SystemTree,
    UserEditDialog,
    Pagination,
  },
  data() {
    const headerContextMenus = {
      width: '120px',
      items: ['sortUp', 'sortDown', 'line', 'cols'],
    }
    return {
      pageData: {
        total: 0,
        page: 1,
        limit: 15,
      },
      activeName: 'first',
      treeData: [],
      userProps: {
        children: 'sysUserGroup',
        label: 'name',
      },
      orgProps: {
        children: 'childUser',
        label: 'username',
      },
      orgData: [
        {
          childUser: [
            {
              username: '',
              childUser: [],
            },
          ],
          username: this.$t('所有用户'),
        },
      ],
      defaultCheckedKeys: [1],
      currentNode: {},
      contextMenuData: [],
      treeLoading: false,
      showCheckbox: false,
      userList: [],
      columns: [
        {
          label: this.$t('用户名'),
          prop: 'username',
          sortable: false,
          align: 'center',
          headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('昵称'),
          prop: 'nickname',
          sortable: false,
          align: 'center',
          headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('角色'),
          prop: 'roleName',
          sortable: false,
          align: 'center',
          headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('分组名称'),
          prop: 'groupName',
          sortable: false,
          align: 'center',
          headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
        {
          label: this.$t('创建日期'),
          prop: 'createdAt',
          sortable: false,
          align: 'center',
          minwidth: 150,
          headerContextMenus: JSON.parse(JSON.stringify(headerContextMenus)),
        },
      ],
      initColsProps: [
        'username',
        'nickname',
        'roleName',
        'groupName',
        'createdAt',
      ],
      actionOpts: {
        show: false,
      },
      initHeadmuneFlag: false,
      tableName: 'userTable',
      requestParam: {
        groupId: 0,
        groupLevel: '',
        current: 1,
        size: 15,
        ordersParam: 'ASC',
        orderType: 1,
        queryType: 0,
        queryParam: '',
      },
      allSize: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      // this.loadNodeTree()
    })
  },
  created() {
    this.$eventBus.$on('doLoadList', this.doLoadList)
    this.$eventBus.$on('doQuery', this.doQueryList)
  },
  beforeDestroy() {
    this.$eventBus.$off('doLoadList')
    this.$eventBus.$off('doQuery')
  },
  methods: {
    // 选择所有页
    handleChangeAllSize(val) {
      this.allSize = val
      this.$refs.userList.clearSelection();
    },
    doRefresh() {
      this.loadUserList({ current: 1 })
      this.$message.success(this.$t('刷新成功'))
    },
    //用户列表回调 处理页面角标相关
    handlePageData(page) {
      this.pageData = page
    },
    //tab切换点击事件
    handleClick(data) {
      if (this.activeName == 'first') {
        this.loadNodeTree()
        console.log('handleClick = first')
      } else {
        this.loadOrgTree()
        console.log('handleClick = second')
      }
    },
    //获取所有用户组
    loadNodeTree(id) {
      let params = {}
      this.$store.dispatch('system/loadUserGroup', params).then((res) => {
        this.treeData = getTreeData(res)
        this.$refs.userTree.updateSelectNode()
      })
    },
    //获取组织架构数据
    loadOrgTree() {
      let params = { groupLevel: 1 }
      this.$store.dispatch('system/loadUserOrg', params).then((res) => {
        this.orgData[0] = res
      })
    },
    // 过滤树
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 点击节点
    nodeClick(node) {
      this.currentNode = node
      this.loadUserList()
      // this.$eventBus.$emit('loadUserList', this.treeNode)
    },
    doLoadList(node) {
      // if (typeof node.id === 'undefined') {
      //   return
      // }
      this.currentNode = node
      this.pageData.page = 1
      this.loadUserList()
      // this.$eventBus.$emit('loadUserList', this.treeNode)
    },
    //搜索
    doQueryList(queryData) {
      this.requestParam.queryType = queryData.queryType
      this.requestParam.queryParam = queryData.queryParam
      this.pageData.page = 1
      this.pageData.limit = 15
      this.loadUserList()
    },
    //用户组tree 调用
    loadUserList(current) {
      if (current) {
        this.pageData = {
          ...this.pageData,
          ...current,
        }
      }
      this.allSize = false
      this.requestParam.groupId = this.currentNode.id || 0
      this.requestParam.groupLevel = this.currentNode.level
      this.requestParam.current = this.pageData.page
      this.requestParam.size = this.pageData.limit
      this.$store
        .dispatch('system/loadUserList', this.requestParam)
        .then((res) => {
          this.userList = res.records ? res.records : []
          this.pageData.total = res.total ? Number(res.total) : 0
        })
        .catch(() => {})
    },
    handleSelectionChange(val) {
      this.$refs.condition.selectChange(val)
    },
    //--------------筛选配置-----------------
    initTable() {
      this.initHeadmuneFlag = true
    },

    handleSort(sortInfo) {
      switch (sortInfo.prop) {
        case 'username':
          this.requestParam.orderType = 1
          break
        case 'nickname':
          this.requestParam.orderType = 2
          break
        case 'roleName':
          this.requestParam.orderType = 3
          break
        case 'groupName':
          this.requestParam.orderType = 4
          break
        case 'createdAt':
          this.requestParam.orderType = 5
          break
        default:
          break
      }
      this.requestParam.ordersParam = sortInfo.type
      this.loadUserList()
      console.log('sortInfo----', sortInfo)
    },
    handleFilter(filter) {
      console.log('filter----', filter)
    },
  },
}
function getTreeData(data) {
  // 循环遍历json数据
  for (var i = 0; i < data.length; i++) {
    if (data[i].sysUserGroup.length < 1) {
      // children若为空数组，则将children设为undefined
      data[i].sysUserGroup = undefined
    } else {
      // children若不为空数组，则继续 递归调用 本方法
      getTreeData(data[i].sysUserGroup)
    }
  }
  return data
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

.leftMain {
  ::v-deep .el-tabs--border-card {
    border: 0 !important;
  }
}
.tabs {
  ::v-deep .el-tabs__item {
    padding: 0 !important;
    width: 125px;
    text-align: center;
  }

  ::v-deep .el-tabs__item:last-child {
    border-right: 0 !important;
  }
}
// ::v-deep .el-tree > .el-tree-node {
//   min-width: 100%;
//   height: calc(100vh - 220px);
//   display: inline-block;
//   overflow-y: scroll;
//   overflow-x: scroll;
// }
// ::v-deep .tree {
//   width: 100%;
//   height: 100%;

//   // scrollbar-width: thin;
// }
// ::v-deep .el-tree-node {
//   position: relative;
//   padding-left: 10px;
// }
</style>
